<?php

defined('_JEXEC') or die('Restricted access');
JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR . '/tables');

class ConsoleModelEventFunnel extends JModelList
{
    /**store
     * @param $inputs
     * @return bool
     */
    public function store($inputs) {
        $inputs['appkey'] = self::getCode();
        $trackDate = JFactory::getDate()->format('Y-m-d H:i:s');
        $db = $this->getDbo();
        $query = $db->getQuery(true);
        $user = JFactory::getUser();
        $query->insert('pp_funnel_cfg')
            ->columns(
                array(
                    $db->quoteName('app_id'), $db->quoteName('name')
                )
            )
            ->values(' "'.$inputs['app_id'].'",  "'.$inputs['name'].'" ' );

        $db->setQuery($query);

        try
        {
            $insertId = $db->execute();
        }
        catch (RuntimeException $e)
        {
            JError::raiseError(500, $e->getMessage());
        }
        $funnel_id = $db->insertid();
        if ($funnel_id) {
            $this->syncItem($funnel_id,$inputs['item']);
        }
        return true;
    }

    public function syncItem($funnel_id, $eventIds=array())
    {
        $this->deleteItem($funnel_id);
        if ($eventIds && is_array($eventIds)) {
            $pos = 0;
            foreach ($eventIds as  $eventId) {
                $this->insertItem($funnel_id, $eventId, $pos);
                $pos++;
            }
        }
    }

    public function deleteItem($funnel_id)
    {
        $db = $this->getDbo();
        $query = $db->getQuery(true);
        $query->delete('pp_funnel_item')

            ->where('funnel_id='.$funnel_id);

        $db->setQuery($query);

        try
        {
            $db->execute();
        }
        catch (RuntimeException $e)
        {
            JError::raiseError(500, $e->getMessage());
        }
        return true;
    }
    public function insertItem($funnel_id, $eventId, $pos) {
        $db = $this->getDbo();
        $query = $db->getQuery(true);
        $query->insert('pp_funnel_item')
            ->columns(
                array(
                    $db->quoteName('funnel_id'), $db->quoteName('event_id'),
                    $db->quoteName('position')
                )
            )
            ->values($funnel_id . ',  "' . $eventId . '", ' . $pos );

        $db->setQuery($query);

        try
        {
            $insertId = $db->execute();
        }
        catch (RuntimeException $e)
        {
            JError::raiseError(500, $e->getMessage());
        }
        $funnel_id = $db->insertid();
        if ($funnel_id) {

        }
        return true;
    }

    /**update
     * @param $inputs
     * @return bool
     */
    public function update($inputs) {
        $id = $inputs['id'];
        $db = $this->getDbo();
        $query = $db->getQuery(true)
            ->update('pp_funnel_cfg')
            ->set("name = '".trim($inputs['name'])."'")
            ->where('id = ' . (int) $id);

        // Set the query and execute the update.
        $db->setQuery($query);

        try
        {
            $db->execute();
        }
        catch (RuntimeException $e)
        {
            JError::raiseError(500, $e->getMessage());
        }
        if ($id) {
            $this->syncItem($id,$inputs['item']);
        }
        return true;
    }


    protected function getListQuery()
    {
        $app = JFactory::getApplication('site');
        $db = $this->getDbo();
        $query = $db->getQuery(true);
        $user = JFactory::getUser();
        $params = $app->getParams();
        $this->setState('params', $params);
        $query->select(
            'fc.*,app.name as appname'
        )
            ->from('pp_funnel_cfg as fc')
            ->join('INNER', 'pp_app AS app ON app.id = fc.app_id')
            ->where('app.account_id='.$user->id);
		$session = JFactory::getSession();
        $appId = $session->get('appId', -1);
        if ($appId > -1) {
        	$query->where('fc.app_id=' . $appId);
        }
        $query->order('fc.name');       

        return $query;
    }

    public function getApp()
    {
        $user = JFactory::getUser();
        $db = $this->getDbo();
        $query = $db->getQuery(true);
        $query->select('*')
            ->from('pp_app')
            ->where('account_id='.$user->id);
        $query->order('id asc');
        $db->setQuery($query);
        $items = $this->_getList($query);
        return $items;
    }
    
    public function getAppOfFunnel($funnel_id) {
    	$db = $this->getDbo();
    	$query = $db->getQuery(true);
    	$query->select('b.*')
    		->from('pp_funnel_cfg a, pp_app b')
    		->where('a.app_id=b.id and a.id=' . $funnel_id);
    	$db->setQuery($query);
    	return $db->loadObject();
    }

    public function getItem($id = null)
    {

        $db = $this->getDbo();
        $query = $db->getQuery(true);
        $query->select('*')
            ->from('pp_funnel_cfg ')
            ->where('id='.$id);
        $db->setQuery($query);
        $Item= $db->loadObject();
        return $Item;
    }

    /**delete
     * @param $id
     */
    public function delete($id)
    {
        $db = $this->getDbo();
        $query = $db->getQuery(true);
        $query->delete('pp_funnel_cfg')

            ->where('id='.$id);

        $db->setQuery($query);

        try
        {
            $db->execute();
        }
        catch (RuntimeException $e)
        {
            JError::raiseError(500, $e->getMessage());
        }
        return true;
    }

    /**获取唯一字符串
     * @return string
     */
    protected static function getCode()
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        return $orderSn;
    }

    public function getEvents($app_id,$notinid='')
    {
        $db = $this->getDbo();
        $query = $db->getQuery(true);
        $query->select('*')
            ->from('pp_event_cfg')
            ->where('app_id='.$app_id);
        if ($notinid) {
            $query->where("event_id not in ($notinid)");
        }
        $query->order('id asc');
        $db->setQuery($query);
        $items = $this->_getList($query);
        return $items;
    }

    public function getFunnelItem($funnel_id,$app_id)
    {
        $db = $this->getDbo();
        $query = $db->getQuery(true);
        $query->select('ec.*')
            ->from('pp_funnel_item fi')
            ->join('INNER', 'pp_event_cfg AS ec ON ec.event_id = fi.event_id')
            ->where('fi.funnel_id='.$funnel_id)
            ->where('ec.app_id='.$app_id);
        $query->order('fi.position asc');
        $db->setQuery($query);
        $items = $this->_getList($query);
        return $items;
    }
}
